package middleware

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/services"
	"GOPAAS/internal/utils"
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Api() gin.HandlerFunc {
	return func(c *gin.Context) {
		access_token := c.GetHeader("access_token")
		user_id_str := c.GetHeader("user_id")
		company_id_str := c.GetHeader("company_id")
		lang := c.GetHeader("lang")
		utils.SetCorsHeader(c)
		_, err := c.Cookie(config.Conf.AppName)
		if err == nil {
			c.Set("login_type", "web")
		} else {
			c.Set("login_type", "api")
		}
		e, b := sentinel.Entry("api_request", sentinel.WithTrafficType(base.Inbound))
		if b != nil {
			fmt.Println("限流了")
			utils.HttpError(c, 503, "请求繁忙", nil)
			c.Abort()
			return
		}
		var user_id int
		var company_id int
		if access_token != "" && user_id_str != "" {
			user_id, _ = strconv.Atoi(user_id_str)
			res := services.IsLogin(int64(user_id), access_token)
			if res {
				//已登录
				if company_id_str != "" {
					company_id, _ = strconv.Atoi(company_id_str)
				}
				user_service := services.GetUserService(int64(user_id))
				user_info, _ := user_service.GetUserInfo()
				if !utils.Int64InArray(user_info.CompanyIds, int64(company_id)) {
					utils.HttpError(c, 403, "非法访问", nil)
					c.Abort()
					return
				}
				var is_inner_user = 0
				if utils.Int64InArray(user_info.Groups, 1) {
					is_inner_user = 1
				}
				if lang == "" {
					lang = user_info.Lang
				}
				c.Set("admin_user", int64(is_inner_user))
				c.Set("user_id", int64(user_id))
				c.Set("company_id", int64(company_id))

			}
		}
		if lang == "" {
			lang = "zh_CN"
		}
		c.Set("lang", lang)
		config.Conf.Host = c.Request.Host
		c.Next()
		e.Exit()
		return
	}
}
